package com.jzo2o.foundations.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.foundations.dto.response.ServeAggregationResDTO;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.mapper.*;
import com.jzo2o.foundations.model.domain.*;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.*;
import com.jzo2o.foundations.service.IServeService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 区域服务管理
 *
 * @author itcast
 * @create 2023/7/17 16:50
 **/
@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {

    @Autowired
    private ServeItemMapper serveItemMapper;

    @Autowired
    private RegionMapper regionMapper;

    @Autowired
    private ServeTypeMapper serveTypeMapper;

    @Autowired
    private ServeSyncMapper serveSyncMapper;

    @Autowired
    private RestHighLevelClient client;

    /**
     * 分页查询服务区域管理
     *
     * @param servePageQueryReqDTO
     * @return
     */
    @Override
    public PageResult<ServeResDTO> findByPage(ServePageQueryReqDTO servePageQueryReqDTO) {

        return PageHelperUtils.selectPage(servePageQueryReqDTO, () -> this.baseMapper.queryListByRegionId(servePageQueryReqDTO.getRegionId()));
    }

    /**
     * 同生共死 在添加服务的数据 如果有一个出现问题 那么所以都不能添加成功
     * 添加区域服务
     *
     * @param dtoList
     */
    @Override
    public void add(List<ServeUpsertReqDTO> dtoList) {
        //创建批量添加的数据集合
        List<Serve> ansList = new ArrayList<>(dtoList.size());
        for (ServeUpsertReqDTO dto : dtoList) {
            //1. 服务项目必须是启用状态的才能添加到区域
            ServeItem serveItem = serveItemMapper.selectById(dto.getServeItemId());
            if (ObjectUtils.isEmpty(serveItem) || serveItem.getActiveStatus() != 2) {
                throw new ForbiddenOperationException("添加失败，服务项目状态有误");
            }
            //2. 一个服务项目对于一个区域，只能添加一次
            int count = this.lambdaQuery()
                    .eq(Serve::getServeItemId, dto.getServeItemId())
                    .eq(Serve::getRegionId, dto.getRegionId())
                    .count();
            if (count > 0) {
                throw new ForbiddenOperationException("添加失败，该区域已添加过该服务");
            }
            //数据处理 拷贝数据
            Serve s = BeanUtils.toBean(dto, Serve.class);
            //根据区域id查询城市编码
            Region region = regionMapper.selectById(dto.getRegionId());
            if (region == null) {
                throw new ForbiddenOperationException("添加失败，区域不存在");
            }
            s.setCityCode(region.getCityCode());
            ansList.add(s);
        }
        //批量保存
        this.saveBatch(ansList);
    }

    /**
     * 删除区域服务
     *
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        //根据id查询服务数据
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtils.isEmpty(serve) || serve.getSaleStatus() != 0) {
            throw new ForbiddenOperationException("删除失败，服务状态有误");
        }
        //进行删除操作
        this.removeById(id);
    }

    /**
     * 上架区域服务
     *
     * @param id
     */
    @Override
    public void onSale(Long id) {
        //1) 区域服务当前非上架状态 (如果当前服务是上架状态就应该报错)
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isNull(serve) || serve.getSaleStatus() == 2) {
            throw new ForbiddenOperationException("当前服务已经是上架状态了");
        }

        //2) 服务项目是启用状态
        //根据服务项目id查询serve_item中active_status
        ServeItem serveItem = serveItemMapper.selectById(serve.getServeItemId());
        if (ObjectUtil.isNull(serveItem) || serveItem.getActiveStatus() != 2) {
            throw new ForbiddenOperationException("服务项目未启用");
        }

        //3) 执行状态字段修改
        serve.setSaleStatus(2);//上架
        baseMapper.updateById(serve);

        //4）添加同步表数据
        addServeSync(id);
    }

    /**
     * 新增服务同步数据
     *
     * @param serveId 服务id
     */
    private void addServeSync(Long serveId) {
        //服务信息
        Serve serve = baseMapper.selectById(serveId);
        //区域信息
        Region region = regionMapper.selectById(serve.getRegionId());
        //服务项信息
        ServeItem serveItem = serveItemMapper.selectById(serve.getServeItemId());
        //服务类型
        ServeType serveType = serveTypeMapper.selectById(serveItem.getServeTypeId());

        ServeSync serveSync = new ServeSync();
        serveSync.setServeTypeId(serveType.getId());
        serveSync.setServeTypeName(serveType.getName());
        serveSync.setServeTypeIcon(serveType.getServeTypeIcon());
        serveSync.setServeTypeImg(serveType.getImg());
        serveSync.setServeTypeSortNum(serveType.getSortNum());

        serveSync.setServeItemId(serveItem.getId());
        serveSync.setServeItemIcon(serveItem.getServeItemIcon());
        serveSync.setServeItemName(serveItem.getName());
        serveSync.setServeItemImg(serveItem.getImg());
        serveSync.setServeItemSortNum(serveItem.getSortNum());
        serveSync.setUnit(serveItem.getUnit());
        serveSync.setDetailImg(serveItem.getDetailImg());
        serveSync.setPrice(serve.getPrice());

        serveSync.setCityCode(region.getCityCode());
        serveSync.setId(serve.getId());
        serveSync.setIsHot(serve.getIsHot());
        serveSyncMapper.insert(serveSync);
    }
    /**
     * 服务区域下架
     *
     * @param id
     */
    @Override
    public void offSale(Long id) {
        //1. 下架成功的必要条件是当前为上架状态
        //  根据id查询服务
        Serve ser = this.getById(id);
        if (ser == null || ser.getSaleStatus() != 2) {
            throw new ForbiddenOperationException("当前服务未处于上架状态");
        }
        // 修改服务区域状态
        UpdateWrapper<Serve> set = new UpdateWrapper<Serve>()
                .eq("id", id)
                .set("sale_status", 1);
        this.update(set);

        //删除同步数据
        serveSyncMapper.deleteById(id);
    }

    /**
     * 设置服务状态为热门
     *
     * @param id
     */
    @Override
    public void onHot(Long id) {
        //根据服务id查询 服务数据
        Serve byId = this.getById(id);
        if (byId == null || byId.getIsHot() != 0) {
            throw new ForbiddenOperationException("当前服务已是热门");
        }
        //根据id 更新状态
        this.lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getIsHot, 1)
                .set(Serve::getHotTimeStamp, System.currentTimeMillis())
                .update();

        //更新数据到同步表
        ServeSync serveSync = new ServeSync();
        serveSync.setId(id);
        serveSync.setIsHot(1);
        serveSync.setHotTimeStamp(System.currentTimeMillis());
        serveSyncMapper.updateById(serveSync);
    }

    /**
     * 取消服务状态为热门
     *
     * @param id
     */
    @Override
    public void offHot(Long id) {
        //根据服务id查询 服务数据
        Serve byId = this.getById(id);
        if (byId == null || byId.getIsHot() != 1) {
            throw new ForbiddenOperationException("当前已服务不是热门");
        }
        this.lambdaUpdate()
                .set(Serve::getIsHot, 0)
                .eq(Serve::getId, id)
                .update();
        //更新数据到同步表- 取消热门同步
        ServeSync serveSync = new ServeSync();
        serveSync.setId(id);
        serveSync.setIsHot(0);
        serveSyncMapper.updateById(serveSync);
    }

    /**
     * 根据区域id 首页服务分类及项目
     *
     * @param regionId
     * @return
     */
    @Override
    @Caching(
            cacheable = {
                    //返回数据为空，则缓存空值30分钟，这样可以避免缓存穿透
                    @Cacheable(value = RedisConstants.CacheName.SERVE_ICON, key ="#regionId" ,
                            unless ="#result.size() > 0",cacheManager = RedisConstants.CacheManager.THIRTY_MINUTES),

                    //返回值不为空，则永久缓存数据
                    @Cacheable(value = RedisConstants.CacheName.SERVE_ICON, key ="#regionId" ,
                            unless ="#result.size() == 0",cacheManager = RedisConstants.CacheManager.FOREVER)
            }
    )
    public List<ServeCategoryResDTO> firstPageServeList(Long regionId) {
        //根据区域id查询id是否存在
        Region region = regionMapper.selectById(regionId);
        if (ObjectUtil.isNull(region)) {
            return CollUtils.emptyList();
        }
        List<ServeCategoryResDTO> scDTOS = this.baseMapper.firstPageServeList(regionId);

        if (CollUtils.isEmpty(scDTOS)) {
            return CollUtils.emptyList();
        }
        List<ServeCategoryResDTO> list = CollUtils.sub(scDTOS, 0, Math.min(scDTOS.size(), 2));

        //遍历 表 而 Steam流里面的foreach 是遍历
        list.forEach(e ->
                //服务项目截取
                e.setServeResDTOList(CollUtil.sub(e.getServeResDTOList(), 0, Math.min(e.getServeResDTOList().size(), 4)))
        );
        return list;
    }

    /**
     * 精选推荐
     *
     * @param regionId
     * @return
     */
    @Override
    @Caching(
            cacheable = {
                    //返回数据为空，则缓存空值30分钟，这样可以避免缓存穿透
                    @Cacheable(value = RedisConstants.CacheName.HOT_SERVE, key ="#regionId" ,
                            unless ="#result.size() > 0",cacheManager = RedisConstants.CacheManager.THIRTY_MINUTES),

                    //返回值不为空，则永久缓存数据
                    @Cacheable(value = RedisConstants.CacheName.HOT_SERVE, key ="#regionId" ,
                            unless ="#result.size() == 0",cacheManager = RedisConstants.CacheManager.FOREVER)
            }
    )
    public List<ServeAggregationSimpleResDTO> hotServeList(Long regionId) {
        Region region = regionMapper.selectById(regionId);
        if (ObjectUtil.isNull(region)) {
            return CollUtils.emptyList();
        }
        return this.baseMapper.hotServeList(regionId);
    }

    /**
     * 根据服务id查询服务详情
     *
     * @param id
     * @return
     */
    @Override
    public ServeAggregationSimpleResDTO findById(Long id) {
        ServeAggregationSimpleResDTO sas = this.baseMapper.findById(id);
        if (ObjectUtils.isEmpty(sas)) {
            throw new ForbiddenOperationException("服务不存在");
        }
        return sas;
    }

    /**
     * 展示服务分类
     *
     * @param regionId
     * @return
     */
    @Override
    public List<ServeAggregationTypeSimpleResDTO> getServeTypeList(Long regionId) {
        //查询区域是否存在
        Region region = regionMapper.selectById(regionId);
        if (ObjectUtil.isNull(region) || region.getActiveStatus() != 2) {
            return Collections.emptyList();
        }
        return this.baseMapper.getServeTypeList(regionId);
    }

    @Override
    public List<ServeSimpleResDTO> search(String cityCode, String keyword, Long serveTypeId) {
        //1. 创建请求对象
        SearchRequest request = new SearchRequest("serve_aggregation");

        //2. 封装请求参数
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //城市编码
        boolQuery.must(QueryBuilders.termQuery("city_code", cityCode));
        //服务类型id
        if (serveTypeId != null) {
            boolQuery.must(QueryBuilders.termQuery("serve_type_id", serveTypeId));
        }
        //关键词
        if (StrUtil.isNotEmpty(keyword)) {
            boolQuery.must(QueryBuilders.multiMatchQuery(keyword, "serve_item_name", "serve_type_name"));
        }
        request.source().query(boolQuery);//查询
        request.source().sort("serve_item_sort_num", SortOrder.ASC);//排序

        //3. 执行请求
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //4. 处理返回结果   List<ServeSimpleResDTO>
        if (response.getHits().getTotalHits().value == 0) {
            return List.of();
        }
        return Arrays.stream(response.getHits().getHits())
                .map(e -> JSONUtil.toBean(e.getSourceAsString(), ServeSimpleResDTO.class))
                .collect(Collectors.toList());
    }
    @Override
    public ServeAggregationResDTO findServeDetailById(Long id) {
        return baseMapper.findServeDetailById(id);
    }
}
